const router = require('koa-router')()
const path = require('path')
const { exec } = require('../db')
// 图片上传接口
// router.post('/api/upload', async (ctx, next) => {
// 	// 1. 接收图片 // 需要一个判断是否传递给后台的一个条件
// 	const file = ctx.request.files.file
// 	console.log('file:', file)
// 	console.log('ctx.origin:,', ctx.origin)
// 	// 2. 拼接路径返回
// 	const filePath = ctx.origin + '/uploads/' + path.basename(file.path)
// 	console.log('filePath:', filePath)
// 	ctx.body = {
// 		code: 0,
// 		msg: 'success',
// 		data: { filePath }
// 	}
// })

// 文章查询
router.get('/api/blogs', async (ctx, next) => {
	// const { id } = ctx.state.userInfo
	const { page = 1, size = 10 } = ctx.query
	const pageData = await exec(`select * from blogs limit ? offset ? `, [
		size * 1,
		(page - 1) * size
	])

	const [count] = await exec(`select count(id) as count from blogs;`)

	ctx.body = {
		code: 0,
		msg: 'success',
		data: { pageData, total: count.count }
	}
})

// 文章增加
router.post('/api/blogs', async (ctx, next) => {
	// comments
	// userId 对应着users表下面的id
	const { userId, title, content, comments = '' } = ctx.request.body
	const insertData = await exec(
		`insert into blogs (userId, title, content, comments) values (?,?,?,?)`,
		[userId, title, content, comments]
	)
	if (insertData.affectedRows) {
		ctx.body = {
			code: 0,
			msg: 'success',
			data: { insertId: insertData.insertId }
		}
	} else {
		ctx.body = {
			code: 0,
			msg: 'fail'
		}
	}
})

// 文章修改
router.put('/api/blogs/:articleId', async (ctx, next) => {
	const { id } = ctx.state.userInfo
	const { articleId } = ctx.params
	const { title = '', content = '', comments = '' } = ctx.request.body
	const updateData = await exec(
		`update blogs set title=? , content=?, comments=? where id=? and userId=?`,
		[title, content, comments, articleId, id]
	)
	if (updateData.affectedRows) {
		ctx.body = {
			code: 0,
			msg: '修改成功'
		}
	} else {
		ctx.body = {
			code: 0,
			msg: '修改失败'
		}
	}
})

// 删除文章接口
router.delete('/api/blogs/:deleteId', async (ctx, next) => {
	// 删除在垃圾桶中，可以恢复删除数据
	// 在数据中，设置一个boolean值，如果删除，就置为false
	// 1 -> 存在 2 => 删除
	const { id } = ctx.state.userInfo
	const { deleteId } = ctx.params
	const deleteData = await exec(
		`update blogs set status=2 where id=? and userId=?`,
		[deleteId, id]
	)
	if (deleteData.affectedRows) {
		ctx.body = {
			code: 0,
			msg: '删除成功'
		}
	} else {
		ctx.body = {
			code: 0,
			msg: '删除失败'
		}
	}
})

module.exports = router
